package com.sun.showcase.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.sun.showcase.utils.LoginContext;
import com.sun.showcase.utils.LoginContextHolder;

/**
 * 日志记录
 *
 */
@Aspect
@Component
public class BussinessLogAop {

	private static final Logger log = LoggerFactory.getLogger(BussinessLogAop.class);

    @Pointcut(value = "@annotation(com.sun.showcase.aop.BussinessLog)")
    public void cutService() {
    }

    @Around("cutService()")
    public Object recordSysLog(ProceedingJoinPoint point) throws Throwable {

        //获取拦截的方法名
        Signature sig = point.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = point.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        String methodName = currentMethod.getName();


        //获取拦截方法的参数
        String className = point.getTarget().getClass().getName();
        Object[] params = point.getArgs();

         //获取操作名称
        BussinessLog annotation = currentMethod.getAnnotation(BussinessLog.class);
        String bussinessName = annotation.name();
       
        StringBuilder sb = new StringBuilder();
        for (Object param : params) {
            sb.append(param);
            sb.append(" & ");
        }
        LoginContext user = LoginContextHolder.get();
        if (null == user) {
        	log.warn("方法名：{}.{}, 参数：{}",className,methodName,sb);
        }else{
        	log.warn("{}=>操作人: {}-{}-{}, 方法名：{}.{}, 参数：{}",bussinessName,user.getUserId(),user.getUserName(),user.getUserNickName(),className,methodName,sb);
        }

        return point.proceed();
    }
}